from django.shortcuts import render
from django.contrib.auth import authenticate # 验证用户名和密码是否合法
from django.contrib.auth import login as user_login
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from .models import UserProfile, EmailVerifyRecord
from django.views.generic import View
from .forms import LoginForm, RegisterForm
from django.contrib.auth.hashers import make_password
from utils.email_send import send_register_email
# Create your views here.


class CustomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))  # 并集的查询
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class LoginView(View):

    def get(self, request):
        return render(request, "login.html", {})

    def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            username = request.POST.get("username", "")
            password = request.POST.get("password", "")
            user = authenticate(username=username, password=password)  # 成功生成对象，否则为None
            if user is not None:  # 登录成功
                if user.is_active:  # 如果账号已经激活，则进行登录。
                    user_login(request, user)
                    return render(request, "index.html")
                else:
                    return render(request, "login.html", {"msg": "用户尚未激活！"})
            else:  # 登录失败
                return render(request, "login.html", {"msg": "用户名密码错误！"})
        else:  # 用户名密码 输入验证失败
            return render(request, "login.html", {"msg": "用户名密码错误！", "login_form": login_form})


class RegisterView(View):
    def get(self, request):
        register_form = RegisterForm()
        return render(request, "register.html", {"register_form": register_form})

    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            username = request.POST.get("email", "")
            if UserProfile.objects.filter(email=username):  # 已经使用过该邮箱注册
                return render(request, "register.html", {"msg": "用户已经注册！", "register_form": register_form})
            password = request.POST.get("password", "")
            user_profile = UserProfile()
            # user_profile.username = username
            user_profile.email = username
            user_profile.password = make_password(password)
            user_profile.is_active = False
            user_profile.save()
            send_register_email(username, "register")
            return render(request, "register.html", {"register_form": register_form})
        else:
            return render(request, "register.html", {"register_form": register_form})


class ActiveUserView(View):
    def get(self, request, active_code):
        # 查询记录是否存在
        all_records = EmailVerifyRecord.objects.filter(code=active_code)
        print("all records found")
        if all_records:
            for record in all_records:
                email = record.email
                print("email:{}".format(email))
                user = UserProfile.objects.get(email=email)
                user.is_active = True
                user.save()
        else:  # active 连接不存在
            return render(request, "active_fail.html", {})
        return render(request, "index.html", {})